<template>
  <ContentWrap>
    <el-form
      ref="ruleFormRef"
      :inline="true"
      :model="ruleForm"
      status-icon
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item :label="t('dataDictionary.dictName')" prop="dictName">
        <el-input v-model="ruleForm.dictName"  autocomplete="off" />
      </el-form-item>
      <el-form-item :label="t('dataDictionary.dictCode')" prop="dictCode">
        <el-input v-model="ruleForm.dictCode"  autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          ><Icon icon="ep:search" class="mr-5px" />{{ t('common.query') }}</el-button
        >
        <el-button @click="resetForm(ruleFormRef)"
          ><Icon icon="ep:refresh-right" class="mr-5px" />{{ t('common.reset') }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-row>
      <el-col>
        <div class="box">
          <el-button type="primary" @click="onAdd()"
            ><Icon icon="material-symbols:add" color="white" />&nbsp;{{
              t('dataDictionary.add')
            }}</el-button
          >
          <el-button type="primary" @click="exportXls"
            ><Icon icon="uil:import" color="white" />&nbsp;{{
              t('dataDictionary.export')
            }}</el-button
          >
          <el-upload
            class="upload-demo"
            :http-request="importData"
            :show-file-list="false"
            accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button type="primary"
              ><Icon icon="mdi:export" color="white" />&nbsp;{{
                t('dataDictionary.import')
              }}</el-button
            >
          </el-upload>
          <el-button type="primary" @click="refreshCache"
            ><Icon icon="ic:sharp-refresh" color="white" />&nbsp;{{
              t('dataDictionary.refreshCache')
            }}</el-button
          >
        </div>
      </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%" v-loading="loading" class="mt-20px">
      <el-table-column type="index" label="#" width="50" />
      <el-table-column :label="t('dataDictionary.dictName')" prop="dictName" />
      <el-table-column :label="t('dataDictionary.dictCode')" prop="dictCode" />
      <el-table-column :label="t('dataDictionary.descriptions')" prop="description" />
      <el-table-column :label="t('workplace.operation')">
        <template #default="scope">
          <div class="btn-all">
            <span @click="onEdit(scope.$index, scope.row)" class="oper-btn"
              ><Icon icon="material-symbols:edit-document-outline-rounded" color="#1890ff" />{{
                t('dataDictionary.edit')
              }}</span
            >
            <i class="line"></i>
            <span class="oper-btn" @click="onSet(scope.row)"
              ><Icon icon="ep:setting" color="#1890ff" />{{ t('dataDictionary.dicSet') }}</span
            >
            <i class="line"></i>

            <el-popover :visible="scope.row.visibleStatus" placement="top" :width="160">
              <p>确定删除吗?</p>
              <div style="text-align: right; margin: 0">
                <el-button size="small" text @click="scope.row.visibleStatus = false">{{
                  t('common.cancel')
                }}</el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="confirmDelete(scope.$index, scope.row)"
                  >{{ t('common.ok') }}</el-button
                >
              </div>
              <template #reference>
                <span @click="handleDelete(scope.$index, scope.row)" class="oper-btn">
                  <Icon icon="material-symbols:delete-outline" color="#1890ff" />{{
                    t('dataDictionary.delete')
                  }}</span
                >
              </template>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="page-content" v-if="total > 0">
      <el-pagination
        v-show="tableData.length > 0"
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <AddData
      ref="addChildren"
      :passStatus="addStatus"
      @add-close="addClose"
      @add-param="addParam"
      :passEditData="passEditData"
    />
    <SideBar ref="sidebarChildren" :dicSet="dicSet" @sidebar-close="sidebarClose" />
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { tableData, sendDataList } from './index'
import { getDataList, dictDelete, getRefleshCache } from '@/api/dataDictionary/index'
import { uploadExcelApi, dictExportXlsAll, downXls } from '@/api/common/import'
import AddData from './components/add.vue'
import SideBar from './components/sidebar.vue'
import { vCheckVal } from '@/directives/checkVal'
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElCol,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
  FormInstance,
  ElPagination
} from 'element-plus'
const { t } = useI18n()
defineOptions({
  name: 'dataDictionary'
})

//search
const ruleFormRef = ref<FormInstance>()
const loading = ref(true)
const ruleForm = reactive({
  dictName: '',
  dictCode: ''
})
// 导入
const importData = async ({ file }) => {
  let rst = await uploadExcelApi(file, '/sys/dict/importExcel')
  let { data } = rst
  if (data.code == 200 && data.success) {
    ElMessage.success('文件上传成功')
    requestData()
  } else {
    ElMessage.error(`文件上传失败，${data.message}`)
  }
}

// 字典配置
let sidebarChildren = ref<InstanceType<typeof SideBar> | null>(null)
let dicSet = ref<boolean>(false)
const onSet = (row) => {
  dicSet.value = true
  sidebarChildren.value?.dictConfig(JSON.parse(JSON.stringify(row)))
  // console.log(row, 2222, sidebarChildren)
}
// 删除
let handleDelete = (ind, row) => {
  // 清空一下其他打开的气泡框
  tableData.value.map((item: any) => {
    item.visibleStatus = false
  })
  row.visibleStatus = true
}
//确定删除
let confirmDelete = async (ind, row) => {
  console.log(ind, row, 'ind,row')
  let result = await dictDelete(row.id)
  if (result.code == '200') {
    row.visibleStatus = false
    requestData()
  }
}
// 打开添加
let addStatus = ref<boolean>(false)
const onAdd = () => {
  addStatus.value = true
  console.log(addStatus.value, 'addStatus')
}
//编辑添加
interface EditData {
  dictName: string
  dictCode: string
  descriptions: string
}
let passEditData = ref<EditData>({
  dictName: '',
  dictCode: '',
  descriptions: ''
})

// 定义子组件名称实例，名称要和ref一样
let addChildren = ref<InstanceType<typeof AddData> | null>(null)
let onEdit = (ind, row) => {
  // 调用子组件方法
  addChildren.value?.getParentParams(JSON.parse(JSON.stringify(row)), true)
  // console.log(JSON.parse(JSON.stringify(row)), '.ruleForm', row)
}
// 接收add组件传值
const addClose = (payload) => {
  addStatus.value = payload
  // console.log(payload, 'payload', addStatus)
}
// 接收add创建成功
const addParam = (payload) => {
  console.log(payload)
  if (payload) {
    requestData()
  }
}
// 接收sidebar组件传值
const sidebarClose = (payload) => {
  dicSet.value = payload
  // console.log(payload, 'dicSet')
}

// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(1)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref(10)
const handleSizeChange = (val: number) => {
  sendDataList.dictName = ruleForm.dictName
  sendDataList.dictCode = ruleForm.dictCode
  sendDataList.pageNo = 1
  currentPage4.value = 1
  sendDataList.pageSize = val
  requestData()
}
const handleCurrentChange = (val: number) => {
  console.log(111, val)
  sendDataList.dictName = ruleForm.dictName
  sendDataList.dictCode = ruleForm.dictCode
  sendDataList.pageNo = val
  requestData()
}
//getData列表 封装

const requestData = async () => {
  // 主列表
  let { result } = await getDataList(sendDataList)
  tableData.value = result.records
  pageSize4.value = result.size
  total.value = result.total
  tableData.value.map((item: any) => {
    item.visibleStatus = false
    return item
  })
  loading.value = false
}
//提交
const submitForm = (formEl: FormInstance | undefined) => {
  console.log(ruleForm)
  // sendDataList
  sendDataList.dictName = ruleForm.dictName
  sendDataList.dictCode = ruleForm.dictCode
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      requestData()
      // console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}
//重置搜索表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  sendDataList.dictName = ruleForm.dictName
  sendDataList.dictCode = ruleForm.dictCode
  requestData()
}

//导出
const exportXls = async () => {
  let data = {
    dictName: ruleForm.dictName,
    dictCode: ruleForm.dictCode,
    pageNo: sendDataList.pageNo,
    pageSize: sendDataList.pageSize
  }
  let result = await dictExportXlsAll('/sys/dict/exportXls', 'post', data, 'blob')
  console.log(result)
  if (result.status == '200') {
    downXls(result, '数据字典', '')
    ElMessage({
      message: result.statusText,
      type: 'success'
    })
  } else {
    ElMessage.error(result.statusText)
  }
}
//刷新缓存
const refreshCache = async () => {
  let result = await getRefleshCache()
  console.log(result)
  if (result.code == '0') {
    requestData()
    ElMessage({
      message: '刷新成功',
      type: 'success'
    })
  } else {
    ElMessage.error(result.message)
  }
}
// table
onMounted(async () => {
  requestData()
})
</script>

<style lang="less" scoped>
@import './index.less';
</style>
